<template>
  <div class="warehouse-container">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 时间查询按钮 -->
      <div class="time-filter-section">
        <div class="time-filter-container">
          <el-button
            v-for="(btn, index) in timeButtons"
            :key="index"
            :type="btn.active ? 'primary' : 'default'"
            @click="handleTimeFilter(btn)"
            class="time-filter-btn"
          >
            {{ btn.label }}
          </el-button>
        </div>
      </div>

      <!-- 图表卡片 -->
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><TrendCharts /></el-icon>
            <span>仓库数据图表</span>
          </div>
        </template>

        <div class="chart-container">
          <div
            ref="chartRef"
            class="chart"
            style="width: 100%; height: 400px"
          ></div>
        </div>
      </el-card>

      <!-- 数据表格卡片 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><List /></el-icon>
            <span>仓库明细数据</span>
            <div class="header-actions">
              <el-button
                type="success"
                @click="handleExport()"
                class="export-btn"
              >
                <el-icon><Download /></el-icon>
                导出
              </el-button>
              <el-button type="primary" @click="getdata()" class="refresh-btn">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="tableData"
          style="width: 100%"
          class="custom-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          :show-summary="true"
          :summary-method="getSummaries"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="warehouse_Name" label="序号" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="warehouse_Name" label="仓库名称" width="150" />
          <el-table-column
            prop="category_NameCount"
            label="货品种类"
            width="120"
          />
          <el-table-column prop="chuPrice" label="初期金额" width="120">
            <template #default="scope">
              <span class="amount-value">¥{{ scope.row.chuPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="moPrice" label="末期金额" width="120">
            <template #default="scope">
              <span class="amount-value">¥{{ scope.row.moPrice }}</span>
            </template>
          </el-table-column>

          <!-- 入库组 -->
          <el-table-column prop="ruwareCiCount" label="入库次数" width="100">
            <template #default="scope">
              <span class="inbound-count">{{ scope.row.ruwareCiCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ruwareCount" label="入库数量" width="100">
            <template #default="scope">
              <span class="inbound-count">{{ scope.row.ruwareCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ruwareprice" label="入库金额" width="120">
            <template #default="scope">
              <span class="inbound-amount">¥{{ scope.row.ruwareprice }}</span>
            </template>
          </el-table-column>

          <!-- 出库组 -->
          <el-table-column prop="chuwareCiCount" label="出库次数" width="100">
            <template #default="scope">
              <span class="outbound-count">{{ scope.row.chuwareCiCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="chuwareCount" label="出库数量" width="100">
            <template #default="scope">
              <span class="outbound-count">{{ scope.row.chuwareCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="chuwareprice" label="出库金额" width="120">
            <template #default="scope">
              <span class="outbound-amount">¥{{ scope.row.chuwareprice }}</span>
            </template>
          </el-table-column>

          <!-- 盘点组 -->
          <el-table-column
            prop="yingStocktakingciCount"
            label="盘点次数（盘盈）"
            width="120"
          >
            <template #default="scope">
              <span class="stocktake-count">{{
                scope.row.yingStocktakingciCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="yingStocktakingCount"
            label="盘点数量（盘盈）"
            width="120"
          >
            <template #default="scope">
              <span class="stocktake-count">{{
                scope.row.yingStocktakingCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="yingStocktakingPrice"
            label="盘点金额（盘盈）"
            width="120"
          >
            <template #default="scope">
              <span class="stocktake-amount"
                >¥{{ scope.row.yingStocktakingPrice }}</span
              >
            </template>
          </el-table-column>

          <!-- 盘亏组 -->
          <el-table-column
            prop="kuiStocktakingciCount"
            label="盘点次数（盘亏）"
            width="120"
          >
            <template #default="scope">
              <span class="stocktake-loss-count">{{
                scope.row.kuiStocktakingciCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="kuiStocktakingCount"
            label="盘点数量（盘亏）"
            width="120"
          >
            <template #default="scope">
              <span class="stocktake-loss-count">{{
                scope.row.kuiStocktakingCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="kuiStocktakingPrice"
            label="盘点金额（盘亏）"
            width="120"
          >
            <template #default="scope">
              <span class="stocktake-loss-amount"
                >¥{{ scope.row.kuiStocktakingPrice }}</span
              >
            </template>
          </el-table-column>

          <!-- 调拨组 -->
          <el-table-column
            prop="diaoRuwareciCount"
            label="调拨次数（调拨入库）"
            width="140"
          >
            <template #default="scope">
              <span class="transfer-in-count">{{
                scope.row.diaoRuwareciCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="diaoRuwareCount"
            label="调拨数量（调拨入库）"
            width="140"
          >
            <template #default="scope">
              <span class="transfer-in-count">{{
                scope.row.diaoRuwareCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="diaoRuwareprice"
            label="调拨金额（调拨入库）"
            width="140"
          >
            <template #default="scope">
              <span class="transfer-in-amount"
                >¥{{ scope.row.diaoRuwareprice }}</span
              >
            </template>
          </el-table-column>

          <el-table-column
            prop="diaoChuwareCiCount"
            label="调拨次数（调拨出库）"
            width="140"
          >
            <template #default="scope">
              <span class="transfer-out-count">{{
                scope.row.diaoChuwareCiCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="diaoChuwareCount"
            label="调拨数量（调拨出库）"
            width="140"
          >
            <template #default="scope">
              <span class="transfer-out-count">{{
                scope.row.diaoChuwareCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="diaoChuwareprice"
            label="调拨金额（调拨出库）"
            width="140"
          >
            <template #default="scope">
              <span class="transfer-out-amount"
                >¥{{ scope.row.diaoChuwareprice }}</span
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            :total="page.totalCount"
            class="custom-pagination"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { reactive, onMounted, ref, watch, computed, nextTick } from "vue";
import { BasicsRed } from "@/http/axiosHelper";
import { ElMessage, ElMessageBox } from "element-plus";
import { BasicsWrite } from "@/http/axiosHelper";
import { useRouter } from "vue-router";
import { StorageRed } from "@/http/axiosHelper";
import {
  Box,
  Search,
  Document,
  Refresh,
  ArrowDown,
  ArrowUp,
  Money,
  List,
  Download,
  Goods,
  User,
  UserFilled,
  Shop,
  TrendCharts,
} from "@element-plus/icons-vue";
import * as echarts from "echarts";

const router = useRouter();
const dialogVisible = ref(false);
const chartRef = ref<HTMLElement>();
let chartInstance: echarts.ECharts | null = null;

// 时间查询按钮配置
const timeButtons = ref([
  { label: "今日", value: "today", active: true },
  { label: "昨日", value: "yesterday", active: false },
  { label: "本周", value: "thisWeek", active: false },
  { label: "上周", value: "lastWeek", active: false },
  { label: "本月", value: "thisMonth", active: false },
  { label: "上月", value: "lastMonth", active: false },
  { label: "最近半年", value: "lastHalfYear", active: false },
  { label: "最近一年", value: "lastYear", active: false },
  { label: "自定义时间", value: "custom", active: false },
]);

// 处理时间筛选
const handleTimeFilter = (btn: any) => {
  timeButtons.value.forEach((b) => (b.active = false));
  btn.active = true;
  getdata(); // 重新获取数据
};

// 定义数据类型接口
interface WarehouseItem {
  warehouse_Name: string;
  category_NameCount: number;
  chuPrice: number;
  moPrice: number;
  ruwareCiCount: number;
  ruwareCount: number;
  ruwareprice: number;
  chuwareCiCount: number;
  chuwareCount: number;
  chuwareprice: number;
  yingStocktakingciCount: number;
  yingStocktakingCount: number;
  yingStocktakingPrice: number;
  kuiStocktakingciCount: number;
  kuiStocktakingCount: number;
  kuiStocktakingPrice: number;
  diaoRuwareciCount: number;
  diaoRuwareCount: number;
  diaoRuwareprice: number;
  diaoChuwareCiCount: number;
  diaoChuwareCount: number;
  diaoChuwareprice: number;
  [key: string]: any; // 允许其他属性
}

// 首先定义所有的响应式数据
const tableData = ref<WarehouseItem[]>([]);
const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
});

const page2 = reactive({
  PageIndex: 1,
  PageSize: 100,
  totalCount: 0,
});

const formInline = reactive({
  Warehouse_Code: "",
  Warehousing_Type: "",
  Warehouse_ID: null,
  Reviewer: "",
  Product_Name: "",
  Category_ID: null,
  Unit_ID: null,
  CreateTimeStartTime: null,
  CreateTimeEndTime: null,
  ReviewTimeStartTime: null,
  ReviewTimeEndTime: null,
  CreateUse: null,
  Department_ID: null,
});

// 其他ref定义
const unit = ref();
const ProductCategory = ref();
const deplarments = ref();
const deplarment = ref();

function formatDate(dateStr: string) {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !tableData.value.length) return;

  const warehouseNames = tableData.value.map((item) => item.warehouse_Name);
  const inboundQuantities = tableData.value.map(
    (item) => item.ruwareCount || 0
  );
  const outboundQuantities = tableData.value.map(
    (item) => item.chuwareCount || 0
  );

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: ["入库数量", "出库数量"],
      top: 30,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        data: warehouseNames,
        axisPointer: {
          type: "shadow",
        },
        axisLabel: {
          rotate: 45,
          color: "#666",
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "数量",
        min: 0,
        axisLabel: {
          formatter: "{value}",
          color: "#666",
        },
      },
    ],
    series: [
      {
        name: "入库数量",
        type: "bar",
        data: inboundQuantities,
        itemStyle: {
          color: "#28a745",
        },
      },
      {
        name: "出库数量",
        type: "bar",
        data: outboundQuantities,
        itemStyle: {
          color: "#667eea",
        },
      },
    ],
  };

  chartInstance.setOption(option);
};

// 表格汇总方法
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (index === 1) {
      sums[index] = "";
      return;
    }
    if (index === 2) {
      sums[index] = "";
      return;
    }
    if (index === 3) {
      sums[index] = "";
      return;
    }
    if (index === 4) {
      sums[index] = "";
      return;
    }

    const values = data.map((item: any) => Number(item[column.property]));
    if (!values.every((value: number) => isNaN(value))) {
      sums[index] = values
        .reduce((prev: number, curr: number) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0)
        .toString();
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

// 仓库汇总导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
  try {
    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await StorageRed({
      url: "/api/WorkOrder/ZongcangkuExport", // 后端接口地址
      method: "GET",
      params: {
        PageIndex: page.PageIndex,
        PageSize: page.PageSize,
      }, // 对应后端 [FromQuery] 的 command 参数
      responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type:
        response.headers["content-type"] ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success("导出成功");
  } catch (error: any) {
    // 处理错误（如后端返回 401/400 等）
    console.error("导出失败：", error.response?.data || error.message);
    ElMessage.error("导出失败，请检查参数或重新登录");
  }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
  const contentDisposition =
    headers["content-disposition"] || headers["Content-Disposition"];
  if (!contentDisposition) return "总仓库管理.xlsx"; // 默认文件名

  // 解码文件名（处理中文编码问题）
  const match = contentDisposition.match(/filename\*?=([^;]+)/);
  if (match) {
    return decodeURIComponent(match[1].replace(/["']/g, ""));
  }
  return "总仓库管理.xlsx";
}

const getdata = () => {
  StorageRed.get("/api/WorkOrder/ZongcangkuHandle", {
    params: {
      PageIndex: page.PageIndex,
      PageSize: page.PageSize,
      
    },
  }).then((res: any) => {
    tableData.value = res.data.data;
    page.totalCount = res.data.totalCount;
  });
};

// 监听器
watch(page, () => {
  getdata();
});

// 监听数据变化，更新图表
watch(
  tableData,
  () => {
    nextTick(() => {
      updateChart();
    });
  },
  { deep: true }
);

onMounted(() => {
  getdata();

  // 初始化图表
  nextTick(() => {
    initChart();
  });
});
</script>

<style scoped>
/* 主容器 */
.warehouse-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 主要内容区域 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-top: 0;
}

/* 时间筛选区域 */
.time-filter-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 24px;
}

/* 时间筛选按钮样式 */
.time-filter-container {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  overflow-x: auto;
  padding: 16px;
}

.time-filter-btn {
  flex-shrink: 0;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  white-space: nowrap;
}

.time-filter-btn.el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.time-filter-btn.el-button--default {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #6c757d;
}

.time-filter-btn.el-button--default:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

/* 图表卡片 */
.chart-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 24px;
}

.chart-container {
  padding: 20px;
}

.chart {
  border-radius: 8px;
  overflow: hidden;
}

/* 表格卡片 */
.table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .el-icon {
  font-size: 20px;
  color: #409eff;
  margin-right: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.export-btn,
.refresh-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  margin-right: 8px;
}

.export-btn {
  background: #f8f9fa;
  border: 2px solid #dee2e6;
  color: #6c757d;
}

.export-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.refresh-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
  color: white;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d6aad 100%);
}

/* 表格样式 */
.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header-wrapper) {
  background: #f8f9fa;
}

.custom-table :deep(.el-table__header) {
  color: #333;
  font-weight: 600;
}

.custom-table :deep(.el-table__body) {
  color: #2c3e50;
}

.custom-table :deep(.el-table__row) {
  color: #2c3e50;
}

.custom-table :deep(.el-table__footer) {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

/* 数据颜色样式 */
.amount-value {
  color: #409eff;
  font-weight: 700;
}

.inbound-count {
  color: #409eff;
  font-weight: 600;
}

.inbound-amount {
  color: #409eff;
  font-weight: 700;
}

.outbound-count {
  color: #67c23a;
  font-weight: 600;
}

.outbound-amount {
  color: #67c23a;
  font-weight: 700;
}

.stocktake-count {
  color: #e6a23c;
  font-weight: 600;
}

.stocktake-amount {
  color: #e6a23c;
  font-weight: 700;
}

.stocktake-loss-count {
  color: #f56c6c;
  font-weight: 600;
}

.stocktake-loss-amount {
  color: #f56c6c;
  font-weight: 700;
}

.transfer-in-count {
  color: #409eff;
  font-weight: 600;
}

.transfer-in-amount {
  color: #409eff;
  font-weight: 700;
}

.transfer-out-count {
  color: #67c23a;
  font-weight: 600;
}

.transfer-out-amount {
  color: #67c23a;
  font-weight: 700;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.custom-pagination {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .warehouse-container {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .export-btn,
  .refresh-btn {
    width: 100%;
  }

  .time-filter-container {
    gap: 4px;
    padding: 12px;
  }

  .time-filter-btn {
    padding: 6px 12px;
    font-size: 12px;
  }

  .chart {
    height: 300px !important;
  }
}
</style>
